﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using tracker.Models;
using tracker.Models.DTO;
using tracker.Models.BLL;
using tracker.Models.DAL;

namespace tracker.Controllers
{
    public class HandlerAddOrRemoveUserController : Controller
    {
        //
        // GET: /HandlerAddOrRemoveUser/
        [CallAjaxFilter]
        public JsonStringResult Index(
            string type,
            string mypermission,
            string userpassword,
            string useraccount, 
            string useraddress, 
            string usercellphone,
            string useremail, 
            string userexpiredtime, 
            string fullname, 
            string usertelephone, 
            string usertrackerlimit,
            string accountstatus,
            string usernote,
            string mode,
            string groupid
            )
        {
            string result = "";
            // Add new
            if (type == "AddNew")
            {
                // Valid input information
                if( Utilities.regexCheck(@"^[\w\d]{6,30}$", useraccount)
                    && Utilities.regexCheck(@"^[\w\d]*$", userpassword)
                    && Utilities.regexCheck(@"^[0-9.]{5,32}$", usercellphone)
                    && Utilities.regexCheck(@"^[0-9.]{5,32}$", usertelephone)
                    && Utilities.emailValid(useremail)
                    && Utilities.regexCheck(@"^[\s\S]{1,255}$", useraddress)
                    && Utilities.isInt(usertrackerlimit)
                    && Utilities.isDateTime(userexpiredtime)
                    && Utilities.isInt(accountstatus)
                    && !String.IsNullOrEmpty(groupid)
                    && new EUserLoginBLL().getBySecurityCode(groupid) !=null // Check parent user is exist
                    && !new EUserLoginBLL().checkExist(useraccount) // Check user account is exist
                    )
                {
                    
                    EUserLogin ent = new EUserLogin();
                    ent.Address = useraddress;
                    ent.CreateBy = Session[Common.USER].ToString();
                    ent.CreateDate = DateTime.Now;
                    ent.Email = useremail;
                    ent.EndDate = DateTime.Parse(userexpiredtime);
                    ent.Fullname = fullname;
                    ent.ModifyBy = "";
                    ent.ModifyDate = DateTime.Now;
                    ent.Note = usernote;
                    ent.NumberOfDevice = int.Parse(usertrackerlimit);
                    ent.Password =Utilities.GetMD5Hash(userpassword);
                    ent.Phone = usertelephone;

                    ent.StartDate = DateTime.Now;
                    ent.Status = int.Parse(accountstatus);
                    ent.TimeZoneMinute = 420;
                    ent.UserGroupID = int.Parse(mypermission);
                    ent.Username = useraccount;
                    ent.Cellphone = usercellphone;
                                       
                    ent.ParentCode = groupid;

                    if (mode.ToLower() == "groupaccount")
                    {
                        // General SecurityCode
                        ent.SecurityCode = "G" + Utilities.createSecurityCode(useraccount).ToUpper();
                        ent.UserGroupID = 4; // Is Group User
                      
                        // Check permission of current user
                        if (Session[Common.USER_GROUPID].ToString() == "3")
                        {
                            if (new UserLoginDAL().insert(ent) == "0")
                            {
                                result = Common.TRUE;
                            }
                            else
                            {
                                result = Common.FALSE;
                            }
                        }
                        else
                        {
                            result = Common.NO_PERISSION;
                        }
                    }
                    else if (mode.ToLower() == "useraccount")
                    {
                        // General SecurityCode
                        ent.SecurityCode = "U" + Utilities.createSecurityCode(useraccount).ToUpper();
                        ent.UserGroupID = 3; // Is Group User

                        // Check permission of current user
                        String currentGroupID = Session[Common.USER_GROUPID].ToString();
                        if (currentGroupID == "1" || currentGroupID == "2")
                        {
                            result = Common.NO_PERISSION;
                        }
                        else if ( currentGroupID== "3")
                        {
                            if (new UserLoginDAL().insert(ent) == "0")
                            {
                                result = Common.TRUE;
                            }
                            else
                            {
                                result = Common.FALSE;
                            }
                        } 
                        else if (currentGroupID == "4")
                        {
                            // Check total device
                            int parentNumDevice = new UserLoginDAL().getNumDeviceBySecurityCode(groupid);
                            int parentSumDevice = new UserLoginDAL().getSumDeviceBySecurityCode(groupid);

                            if (parentSumDevice + ent.NumberOfDevice > parentNumDevice)
                            {
                                result = "maxlimit";
                            }
                            else
                            {
                                if (new UserLoginDAL().insert(ent) == "0")
                                {
                                    result = Common.TRUE;
                                }
                                else
                                {
                                    result = Common.FALSE;
                                }
                            }
                        }
                        else
                        {
                            result = Common.NO_PERISSION;
                        }
                    }
                }
            }
            else if (type == "AddOld")
            {

                if (string.IsNullOrEmpty(groupid)
                    || string.IsNullOrEmpty(useraccount)
                    || string.IsNullOrEmpty(userpassword))
                {
                    result = Common.FALSE;
                }
                else
                {
                    UserLoginDAL dal = new UserLoginDAL();
                    String tmp = dal.changeParent(groupid, useraccount, Utilities.GetMD5Hash(userpassword));
                    if (tmp == "0")
                    {
                        result = Common.TRUE;
                    }
                    else
                    {
                        result = Common.FALSE;
                    }
                }
            }
            result = Utilities.createJSON("success", result);
            return new JsonStringResult(result);
        }
        public JsonStringResult Remove(string groupid, string useraccounts, string deltype)
        {
            string result = "";
            if (String.IsNullOrEmpty(groupid) || String.IsNullOrEmpty(useraccounts) || String.IsNullOrEmpty(deltype))
            {
                result = Common.FALSE;
            }
            else
            {
                string currentUserGroup = Session[Common.USER_GROUPID].ToString();
                
                // Build SP parameter: x1, x2, x3  --> 'x1', 'x2', 'x3'
                string userList = useraccounts.Replace(" ","");
                string[] m = userList.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                userList = "";
                for (int i = 0; i < m.Length; i++)
                {
                    userList += "'" + m[i] + "'";
                    if (i < m.Length - 1)
                    {
                        userList += ",";
                    }
                }

                if (currentUserGroup == "3")
                {
                    result = new UserLoginDAL().deleteMultipUserByUsername(userList, deltype).ToString();
                }
                else if (currentUserGroup == "4")
                {
                    // Group user
                    // Check groupid is current user
                    if (groupid == Session[Common.USER_SECUTIRY_CODE].ToString())
                    {
                        result = new UserLoginDAL().deleteMultipUserByUsername(userList, deltype).ToString();
                    }
                    else
                    {
                        //permission or fail
                        result = Common.IS_ERROR;
                    }

                }
            }
            if (result == "1")
            {
                result = Common.TRUE;
            }
            else
            {
                result = Common.FALSE;
            }
            result = Utilities.createJSON(Common.SUCCESS, result);
            return new JsonStringResult(result);
        }
    }
}
